package com.grade.system.controller;

import com.grade.system.entity.User;
import com.grade.system.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
public class UserRestController {

    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/aj_login")
    @ResponseBody
    public User login(String name, String pwd) {
        return userMapper.selUserByNameAndPwd(name, pwd);
    }

    @RequestMapping("/aj_register")
    public int register(@RequestParam Map<String, Object> map) {
        String name = String.valueOf(map.get("name"));
        String pwd = String.valueOf(map.get("pwd"));
        int status = Integer.parseInt(String.valueOf(map.get("status")));
        User user = userMapper.selUserByName(name);
        if (user != null) {
            return NetState.STATE_EXISTS.value;
        }
        user = new User(name, pwd, status);
        return userMapper.insUser(user) ? NetState.STATE_OK.value : NetState.STATE_ERROR.value;
    }

    @RequestMapping("/aj_sel_user_by_all")
    @ResponseBody
    public List<User> selUserByAll() {
        return userMapper.selUserByAll();
    }

    @RequestMapping("/aj_user_by_id")
    @ResponseBody
    public User selUserById(int id) {
        return userMapper.selUserById(id);
    }

    @RequestMapping("/aj_del_user_by_id")
    @ResponseBody
    public int delUserById(@RequestParam Map<String, Object> map) {
        int id = Integer.parseInt(String.valueOf(map.get("id")));
        return userMapper.delUserById(id) ? NetState.STATE_OK.value : NetState.STATE_ERROR.value;
    }
}
